package com.heatup.apt.api.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.heatup.apt.api.service.CoachService;
import com.heatup.apt.api.service.DataDictService;
import com.heatup.apt.common.constants.*;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.model.DataDict;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.coach.*;
import com.heatup.apt.model.management.CoachInf;
import com.heatup.apt.model.order.PresalePrivateCourseOrderModel;
import com.heatup.apt.model.order.PrivOrderDetailResultModel;
import com.heatup.apt.model.user.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.heatup.apt.api.service.CoachCourseFeeService;
import com.heatup.apt.api.service.IndexResourceService;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.common.dao.coach.CoachStarMapper;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.model.BannerActivityApiModel;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.ResourceExample;
import com.heatup.apt.model.api.ResourceModel;
import com.heatup.apt.model.api.coach.CoachResultModel;
import com.heatup.apt.model.api.coupon.CouponApiResultModel;
import com.heatup.apt.model.course.CourseInfoModel;
import com.heatup.apt.model.course.CoursePrivteFeeVO;

/**
 * 教练详情
 * Created by b3st9u on 16/8/20.
 */
@Service
public class CoachServiceImpl extends SuperServiceImpl<CoachInfoMapper, CoachInfo> implements CoachService {
    protected static final Logger logger = LoggerFactory.getLogger(CoachServiceImpl.class);

    @Autowired
    private CoachInfoMapper coachInfoMapper;

    @Autowired
    private CoachStarMapper coachStarMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private OperativeMapper operativeMapper;//教练

    @Autowired
    private CourseSignMapper courseSignMapper;

    @Autowired
    private CoachSigninLogMapper coachSigninLogMapper;

    @Autowired
    private CoachCourseFeeService coachCourseFeeService;
    
    @Autowired
    private CourseStandardMapper courseStandardMapper;
    
    @Autowired
    private CoachCaseMapper coachCaseMapper;
    
    @Autowired
    private IndexResourceService indexResourceService;
    
    @Autowired
    private CourseInfoMapper courseInfoMapper;
    
    @Autowired
    private CouponDetailMapper couponDetailMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    
    @Autowired
    private DataDictService dataDictService;

    @Autowired
    private PrivOrderDetailResultModelMapper privOrderDetailResultModelMapper;

    @Override
    public CoachResultModel queryCoachById(int id,int userId) {
        CoachResultModel coachResultModel = null;
        CoachInfo coachInfo = coachInfoMapper.queryCoachByID(id);
        if (coachInfo != null) {
            coachResultModel = new CoachResultModel();
            coachResultModel.setId(coachInfo.getId());
            coachResultModel.setAuthInfo(coachInfo.getAuthInfo().replace("、", "#"));
            coachResultModel.setBackgroundsUrl(coachInfo.getBackgroundsUrl());
            coachResultModel.setHeadImg(coachInfo.getHeadImg());
            coachResultModel.setBriefing(coachInfo.getBriefing());
            coachResultModel.setNickName(coachInfo.getNickName());
            coachResultModel.setGender(coachInfo.getGender());
            coachResultModel.setMobile(coachInfo.getMobile());
            coachResultModel.setIsCamp(coachInfo.getIsCamp());
            coachResultModel.setIsPrivate(coachInfo.getIsPrivate());
            coachResultModel.setIsTeam(coachInfo.getIsTeam());
            coachResultModel.setPersonalStatus(coachInfo.getPersonalStatus());
            coachResultModel.setCourseId(coachInfo.getCourseId() == null ? 0 : coachInfo.getCourseId());
            coachResultModel.setIsPrivateBodyExamination(coachInfo.getIsPrivateBodyExamination());
            coachResultModel.setIsPrivateExperience(coachInfo.getIsPrivateExperience());
            coachResultModel.setIsPrivateConsult(coachInfo.getIsPrivateConsult());
            coachResultModel.setIsPrivateCoachSort(coachInfo.getIsPrivateCoachSort());
            coachResultModel.setRetailBeginTime(dataDictService.getBookRetailBeginTime());
            coachResultModel.setNowDate(DateUtils.getDateShort(new Date()));
            int count = coachInfoMapper.querySecretCourseCountByCoachId(Long.valueOf(id));
            coachResultModel.setSecretCourseCount(count);  //返回该教练正在上的私教课数量

            if (coachInfo.getResources() != null && coachInfo.getResources().size() > 0) {
                List<Resource> coachResource = coachInfo.getResources();
                for (Resource resource : coachResource) {
                    if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("coach_video")) {
                        coachResultModel.setLink(resource.getLink());
                        coachResultModel.setUrl(resource.getUrl());
                    }
                }
            }

            String tags = coachInfo.getTags();
            if (!Strings.isNullOrEmpty(tags)) {
                coachResultModel.setTags(Arrays.asList(tags.split("#")));
            }
            if (StringUtils.isNotBlank(coachInfo.getGoodCourse())) {
                coachResultModel.setGoodCourse(Arrays.asList(coachInfo.getGoodCourse().split("#")));
            }
            //教练星级
            CoachStar coachStar = coachStarMapper.selectByCoachId(id);
            float star = 0;
            if (coachStar != null) {
                star = coachStar.getStar();
            }
            coachResultModel.setStar((float) (Math.round(star * 100)) / 100);
            //资源信息
            coachResultModel.setResourcesList(selectResourceByCoachId(id));
            // 所授课程 这里有改动 所受课程改变为教练课上的私教课程
            if(coachInfo.getIsPrivate() == 1){
//            	coachResultModel.setTeachCourseList(coachInfoMapper.queryPtCoachOngoingCourseByCoachId(id));
            	List<String> nameList =  Arrays.asList(coachInfo.getTeachCourse().split("#"));
            	coachResultModel.setTeachCourseList(courseStandardMapper.queryCourseStandardListByName(nameList));
            }
            // 私教案例
            List<CoachCase> coachCaseList = coachCaseMapper.queryCoachCaseByCoachId(coachInfo.getId());
            if(coachCaseList !=null && coachCaseList.size()>0){
                coachResultModel.setCoachCaseList(coachCaseList);
            }
            // 特惠活动
            List<CourseInfoModel> discountActivitiesList = courseInfoMapper.getSecretExperienceAndPhysicalExaminationCourse();
            List<BannerActivityApiModel> bannerModelList = new ArrayList<>();
            // 如果该教练不支持 体测 或者 体验课程 则对应的特惠活动也不显示
			for (CourseInfoModel model : discountActivitiesList) {
				
				if ((coachInfo.getIsPrivateBodyExamination() == null 
						&& CourseConstants.CourseType.physical_coupon.getType().equals(model.getCourseType())
						|| CourseConstants.CourseType.physical_coupon.getType().equals(model.getCourseType())
								&& coachInfo.getIsPrivateBodyExamination() != 1)
						|| (coachInfo.getIsPrivateExperience() == null 
								&& CourseConstants.CourseType.private_physical.getType().equals(model.getCourseType())
								|| CourseConstants.CourseType.private_physical.getType().equals(model.getCourseType())
										&& coachInfo.getIsPrivateExperience() != 1))
					continue;
            	
            	CouponApiResultModel couponApiResultModel = couponDetailMapper.queryAboutSecretCouponDetail(userId,Integer.valueOf(model.getCourseType()));
            	BannerActivityApiModel banner = new BannerActivityApiModel();
            	banner.setId(model.getId());
            	banner.setImgUrl(model.getResources().get(0).getUrl());
            	banner.setLink(model.getLink());
            	banner.setTitle(model.getTitle());
            	banner.setServiceId(model.getServicePrice().getId());
            	banner.setCourseId(model.getId());
            	banner.setServiceType(model.getServicePrice().getServiceType());
            	banner.setPrice(model.getServicePrice().getPrice());
            	if(couponApiResultModel != null){
            		banner.setIsHaveCoupon(1);
            		banner.setCouponType(couponApiResultModel.getCoupon_type());
            		if(couponApiResultModel.getCoupon_type().intValue() == CouponConstants.CouponType_Money){
            			banner.setCouponName("用券减"+couponApiResultModel.getCash_money()+"元");
            		}else{
            			banner.setCouponName("用券免费");
            		}
            		
            		banner.setCashMoney(couponApiResultModel.getCash_money());
            	}else{
            		banner.setIsHaveCoupon(0);
            	}
            	bannerModelList.add(banner);
            }
            coachResultModel.setDiscountActivitiesList(bannerModelList);
            
        }
        return coachResultModel;
    }

    /**
     * 根据教练id查询教练对应图片/视频／文章
     *
     * @param id
     * @return
     */
    public Map<String, Object> selectResourceByCoachId(int id) {
        ResourceExample resourceExample = new ResourceExample();
        resourceExample.or().andParentIdEqualTo(id).andParentTypeEqualTo("3").andResKeyNotEqualTo("coach_private_sample");//查询图片资源;
        List<Resource> resources = resourceMapper.selectByExample(resourceExample);

        Map<String, Object> resourceMap = new HashMap<>();
//        List<Articlescrap> articleList = operativeMapper.queryArticlescrapListByAuthorId(id);
        resourceMap.put("article", indexResourceService.queryIndexResourcePrivateArticle(id));
        /*if (articleList != null && articleList.size() > 0) {

            resourceMap.put("article", articleList);
        }*/
        if (resources != null && resources.size() > 0) {
            for (Resource resource : resources) {
                List<Object> resourceModels;
                String type = ResourceContants.ResourceResTypeEnum.getResType(resource.getResType()).getTitle();
                if (!Strings.isNullOrEmpty(resource.getResKey()) && resource.getResKey().equals("top_banner")) {
                    type = resource.getResKey();
                }
                if (resourceMap.containsKey(type)) {
                    resourceModels = (List<Object>) resourceMap.get(type);
                } else {
                    resourceModels = Lists.newArrayList();
                }
                ResourceModel resourceModel = new ResourceModel();
                resourceModel.setUrl(resource.getUrl());
                resourceModel.setTitle(resource.getTitle());
                resourceModel.setLink(resource.getLink());
                resourceModel.setId(resource.getId());
                resourceModels.add(resourceModel);
                resourceMap.put(type, resourceModels);
            }

        }

        return resourceMap;


    }


    /**
     * 根据教练手机号码 查询教练信息
     *
     * @param mobile 手机号码
     * @return
     */
    @Override
    public CoachInfo queryCoachByMobile(String mobile) {
        return coachInfoMapper.queryCoachByMobile(mobile);
    }

    /**
     * 根据教练手机号码 查询教练信息及进店密码
     *
     * @param mobile 手机号码
     * @return
     */
    @Override
    public CoachInfo queryCoachAndPwdByMobile(String mobile) {

        CoachInfo coachInfo = null;
        if (StringUtils.isNotBlank(mobile)) {
            coachInfo = coachInfoMapper.queryCoachByMobile(mobile);
//            if (coachInfo != null) { //暂时不查询教练课时费...
                //查询教练所有课时费合计
//                CoachCourseFeeVO coachCourseFeeVO = new CoachCourseFeeVO();
//                coachCourseFeeVO.setCoachId(coachInfo.getId());
//                coachInfo.setTotalTotalSum(coachCourseFeeService.queryCoachFeeTotalSum(coachCourseFeeVO));
//            }
        }
        return coachInfo;
    }

    @Override
    public List<CoursePrivteFeeVO> queryCoachPrivateFeeDetail(Map<String, Object> paramsMap) {
    	return courseSignMapper.queryPrivateCoachFee(paramsMap);
    }

    @Override
    public Map<String, Object> queryCoachCampFeeDetail(Map<String, Object> paramsMap) {
        Map<String, Object> map = new HashMap<>();
        List<CampCountFeeDetail> list = coachSigninLogMapper.queryCampCoachFee(paramsMap);
//        int totalCount = coachSigninLogMapper.queryCampCoachCount(paramsMap);
        map.put("campList", list);
//        map.put("campCount", totalCount);
        return map;
    }

    /**
     * 查询教练课时费中的补贴/扣费月度详情
     *
     * @param mobile 教练手机号
     * @param year   查询年
     * @param month  查询月
     * @return 返回教练课时费中的补贴/扣费月度详情
     */
    @Override
    public JSONObject queryCoachAdjustFeeMonth(String mobile, Integer year, Integer month) {

        return coachCourseFeeService.queryCoachAdjustFeeMonth(mobile, year, month);
    }
    
    /**
     * 根据门店查询私教
     */
	@Override
	public Map<String, Object> queryCoachPrivateList(Map<String, Object> paramsMap) {

		paramsMap.put("coachList", coachInfoMapper.queryCoachPrivateListByStoreId(paramsMap));
		paramsMap.put("privateBannerList", indexResourceService.queryIndexResourcePrivateBannerList());
		paramsMap.put("retailBeginTime", dataDictService.getBookRetailBeginTime());
		paramsMap.put("nowDate", DateUtils.getDateShort(new Date()));
		return paramsMap;
	}

    /**
     * 查询私教订单限制
     *
     * @param serviceType  9 体测 10 体验
     * @author blank 2017/8/24 下午6:29
     */
    @Override
    public Map<String, Object> queryPrivateOrderLimit(Integer serviceType) {

        if (serviceType == null ) throw new IllegalArgumentException("serviceType can not be null!");

        Map<String, Object> resultMap = new HashMap<>();

        if (serviceType == ServiceConstans.ServiceType.physicalCoupon.getIndex()) {
            //9 体测
            resultMap.put("isCanOrderLimit", orderInfoMapper.queryPrivateBodyExaminationOrderMaxLimitByToDay());
            resultMap.put("privateOrderLeft", orderInfoMapper.queryPrivateBodyExaminationOrderLeftCountByToDay());


        } else if (serviceType == ServiceConstans.ServiceType.privatePhysical.getIndex()){
            //10 体验
            resultMap.put("isCanOrderLimit", orderInfoMapper.queryPrivateExperienceOrderMaxLimitByToDay());
            resultMap.put("privateOrderLeft", orderInfoMapper.queryPrivateExperienceOrderLeftCountByToDay());

        }

        return resultMap;
    }

    @Override
    public List<CoachBriefResultModel> queryCoachTeamList(String mobile, Integer isPrivateCoach) {

        Map<String,Object> paraMap = new HashMap<>();
        paraMap.put("mobile",mobile);
        if(isPrivateCoach == 1) paraMap.put("isPrivate",1);

        return coachInfoMapper.queryCoachTeamList(paraMap);

    }

    @Override
    public ApiResultModel getOpendBillingParam(UserInfo userInfo) {
        ApiResultModel<Object> model = new ApiResultModel<>();
        // step 1 查询字典表里面的数据 就是私教课程类型属性
        List<DataDict> dataDicts = dataDictService.queryDataDicts("COURSE_ATTR");
        CoachInfo coachInfo = coachInfoMapper.queryCoachByMobile(userInfo.getMobile());

        // 查询教练
        if (coachInfo == null){
            model.setErrorCode(ErrorCodeConstants.Code.COACH_NOT_MATCH.getCode());
            model.setMsg(ErrorCodeConstants.Code.COACH_NOT_MATCH.getMessage());
            model.setData(ErrorCodeConstants.Code.COACH_NOT_MATCH.getMessage());
            return model;
        }
        Map<String,Object> resultMap = new HashMap<>();
        if(coachInfo != null && "1".equals(coachInfo.getStatus())){

            // queryCoachTeamList
            List<CoachBriefResultModel> coachList = queryCoachTeamList(userInfo.getMobile(), 1);
            resultMap.put("courseList",dataDicts);
            resultMap.put("coachList",coachList);
            model.setData(resultMap);
        }
        model.setRet(model.RET_SUCCESS);
        return model;
    }

    @Override
    public ApiResultModel chiefCoachQueryCoachTeamList(UserInfo userInfo) {
        ApiResultModel<Object> resultModel = new ApiResultModel<>();
        Map<String,Object> resultMap = new HashMap<>();

        CoachInfo coachInfo = coachInfoMapper.queryCoachByMobile(userInfo.getMobile());
        if(coachInfo == null){
            resultModel.setRet(resultModel.RET_ERROR);
            resultModel.setMsg(ErrorCodeConstants.Code.COACH_NOT_MATCH.getMessage());
            resultModel.setErrorCode(ErrorCodeConstants.Code.COACH_NOT_MATCH.getCode());
            return resultModel;
        }

        // 判断是不是主教练
        if(coachInfo.getIsChiefCoach() != 1){
            resultModel.setRet(resultModel.RET_ERROR);
            resultModel.setMsg(ErrorCodeConstants.Code.NOT_HAS_PERMISSIONS.getMessage());
            resultModel.setErrorCode(ErrorCodeConstants.Code.NOT_HAS_PERMISSIONS.getCode());
            return resultModel;
        }

        List<CoachBriefResultModel> list = this.queryCoachTeamList(userInfo.getMobile(), 2);
        for (CoachBriefResultModel model : list){
            if (model.getCoachId() == coachInfo.getId()){
                list.remove(model);
                break;
            }
        }

        resultMap.put("coachList",list);
        resultModel.setData(resultMap);
        resultModel.setRet(resultModel.RET_SUCCESS);
        return resultModel;
    }


}
